/*Dependence: permission.js*/

var gData = {};  // cache the id information , static data and quote data for each ticker.
var gIdMap = {}; // map the performance id or sec id to gkey. gkey = tenfore exchange code +":"+ tenfore ticker.

/* Set Separator for proctol of subscribe to push and pull server*/
if (typeof(push) == "undefined") {
    push = {};
}
if(typeof(push.subSeparator)== "undefined"){  //not defined in web config file.
    push.subSeparator = "|";
}
if (typeof(pull) == "undefined") {
    pull = {};
}
if(typeof(pull.subSeparator)== "undefined"){
    pull.subSeparator = "_";
}
/* Pull or Push mode setting*/
if(typeof(PULL_Path)=="undefined"){
	PULL_Path="/pullservice/pull/";
}
function checkPullPermission(){
    if(typeof(GOLBAL_DATA.ModulePermission)!="undefined"){
        var idx=$.inArray(-1.01,GOLBAL_DATA.ModulePermission);
        if(idx>-1){
            return true;
        }
    }
    return false;
}

var DATA_TYPES=["delay","mix"];//,"fast","slow","slower","slowest"];//["delay","bats"];
if(checkPullPermission()){
    DATA_TYPES=DATA_TYPES.concat(["fast","slow","slower","slowest"]);
}
var PULL_DATA_RATE={"fast":5,"slow":10,"slower":15,"slowest":30};
if(typeof(QS_DataType)=="undefined"){
    QS_DataType = "mix";
}
if(QS_DataType=="PULL"){
    QS_DataType="slow";
}
if(QS_DataType=="PUSH"){
    QS_DataType="mix";
}
if($.inArray(QS_DataType,DATA_TYPES)==-1){
    QS_DataType="mix";
}

/* convert MS security type to tenfore security type.*/
function toStockTypeCode(ty,tenforeCode,tenforeType){  
   if(typeof(tenforeType)!="undefined"&&!isNaN(tenforeType)){
	 return tenforeType;
  }
  if(ty == null) return 1;
  var t = ty.toUpperCase();
   if (t == "ST"){ // stock
      return "1";
   } else if (t == "XI"){// Index
      return "10";      
  } else  if( t == "FE"||t=="FC") {  // ETF 
     return "1";
  }else if(t == "FO"){  // FC: close fund, FO: open fund.
     return "8";
  }else if(t=="--"||t==""){  // 33 is the index exchange. some index has no pid and morningstar security type
      return tenforeCode==33?"10":"1";
  }else {
      return "1";
  }
}


/* Market widgets from Site Builder settings*/
var STATIC_VAR={marketIndexSessionExists:false,marketsFirstLoad:false,watchlistTitileMaxLength:60};

//Tips
var QSTIPs = [];
QSTIPs[0] = {'title': QS_Lang.text["tips_title1"],'content':'<img src="help/Tip1_Getting_Started.png" width="948" height="752" />'};
QSTIPs[1] = {'title': QS_Lang.text["tips_title2"],'content':'<img src="help/Tip2_Add_New_Workspace.png" width="948" height="752" />'};
QSTIPs[2] = {'title': QS_Lang.text["tips_title3"],'content':'<img src="help/Tip3_Create_New_Workspace.png" width="948" height="752" />'};
/* URLs and function for ID service and static field service*/
//var getTickerUrl = QS_PROTOCOL + "qt.morningstar.com/switchservice/getids.ashx?d=1&symbol="; // URL for ID service
var getTickerUrl = version.domain + "getids.jsp?symbol=";
var getSqUrl = "getStaticData.jsp";  // URL for static service.
var getSqXMLUrl = "getStaticDataFromXML.jsp"; // URL for XML static fields service.
var xmlDataPoint=['S8','S12','S19','S36','S214','S555','S676','S695','S696','S697','S698','S700','S702','S703',
    'S704','S705','S706','S707','S708','S709','S710','S711','S712','S713','S714','S715','S716','S717','S718',
    'S719','S1011','S1013','S1018','S1041','S1042','S1043','S1076','S1077','S1086','S1087','S1088','S1315'];
    
function checkTickerInfo(symbol, callback) {  // request ID service
    if (symbol == "") return false;  
    if (symbol.length > 1000) { //seperate single request to several requests for long url - david
        var symbolArray = symbol.split(',');
        var symbolStrs = [];
        var maxTicker = 100;
        var c = Math.ceil(symbolArray.length / maxTicker); 
        var cbNum = 0;
        var returnArray = [];
        for (var i = 0; i < c; i++) {
            symbolStrs.push(symbolArray.slice(maxTicker * i, maxTicker * (i + 1)).join(','));
            $.getJSON(getTickerUrl + symbolStrs[i] + "&cb=?",function(o){
                cbNum++;
                returnArray = returnArray.concat(o.Records); //merge the return
                if (cbNum >= c) {
                    callback({
                        'Records': returnArray
                    });
                }
            });
            
        }
    } else {
        $.getJSON(getTickerUrl + symbol + "&cb=?",callback);
    }
}

function getStaticData(symbol, callback) {
    if (symbol == null||!symbol.length) {callback(false);return;}
    var secIds = [],sec, gkey ,secIdsMap={};
    for(var i=0;i<symbol.length;i++){ // pick up the sec id for each symbol in list and remove the repeated symbol.
        if(typeof(symbol[i])=="undefined" ||symbol[i]==""){continue;}
        gkey=gIdMap[symbol[i]];
        if(typeof gkey=='undefined'||(gData[gkey] && gData[gkey]["hasStaticData"])){continue;}
        sec=gData[gkey]["secId"]||symbol[i];//symbol is pid
        if(!secIdsMap[sec]){
            secIds.push(sec);
            secIdsMap[sec]=true;
        }       
    }
    if (secIds.length == 0) {callback(false);return;}
    $.post(getSqUrl, {
        'secId': secIds.join(",")
    }, function(o){
        o = $.evalJSON(o);
        if (!o || !o.data || o.data.length < 1) {
            callback(o);
            return;
        }else {
            var d = o.data, mkey, dr,ecode;
            for (var i = 0; i < d.length; i++) { // store static data to gData.
                mkey = d[i].secId;
                if (!gIdMap[mkey]) 
                    continue;
                if (!gData[gIdMap[mkey]]) 
                    gData[gIdMap[mkey]] = {};
                dr = gData[gIdMap[mkey]];
                ecode = dr["tenforeCode"];
                for (var j in d[i]) {
					if(j=="pd001"||j=="pd003"||j=="pd005"||j=="pd007"||j=="pd009"||j=="pd00b"||j=="pd00d"||j=="pd00f"||
					   j=="pd00h"||j=="pd014"||j=="pm493"||j=="pm494"||j=="pm495"){  // convert to two decimal for return value.
					   dr[j] = isNaN(d[i][j])?"":parseFloat(d[i][j]).toFixed(2);
					}else{
						dr[j] = d[i][j];
					}
                }
                if (dr['rr01y']) { //merge fund's Rating to ST's st200
                    dr['st200'] = dr['rr01y'];
                }
				if(dr["mType"]!="FE"&&dr["mType"]!="FC"){
	                if (dr['os70c']) { //merge fund's 52 wk high to ST's ST168
	                    dr['st168'] = dr['os70c'];
	                }
	                if (dr['os70e']) { //merge fund's 52 wk low to ST's ST169
	                    dr['st169'] = dr['os70e'];
	                }
	                if (dr['os70d']) { //merge fund's 52 wk high(date) to ST's ST109
	                    dr['st109'] = dr['os70d'];
	                }
	                if (dr['os70f']) { //merge fund's 52 wk low(date) to ST's ST106
	                    dr['st106'] = dr['os70f'];
	                }
				}
                if(dr['la03z']){//map to key
                    dr['la03z'] = LA03Z[dr['la03z']] || '';
                }
                if (dr['os378']) { //map to string - david
                    dr['os378'] = QS_DateFmt.Mo[dr['os378']-1] || '';
                }
                if (ecode == "27") { // MSCI indexs
                    dr["LastPrice"] = dr["os065"]==""?"":parseFloat(dr["os065"]); // daily price to last price.
                    dr["Chg%"] = dr["pd003"]==""?"":parseFloat(dr["pd003"]);
                    dr["Chg"]= (dr["LastPrice"]!=""&&dr["Chg%"]!="")?dr["LastPrice"]*dr["Chg%"]/100:"";
                }
                dr["hasStaticData"] = true;
				if(dr["mType"]=="ST"&&dr["currency"]=="GBP"){  // change the currency from GBP to GBX for stock in Lodon exchanges.
				   dr["currency"] = "GBX";
				   dr["st168"] = dr["st168"]*100;  // 52 w high
				   dr["st169"] = dr["st169"]*100;  // 52 w low;
				}
            }
            callback(o);
        }
    });
}

function getStaticDataFromXML(symbol,callback){
    if (symbol == null||!symbol.length) return;
    $.post(getSqXMLUrl, {t:symbol},function(o){
        o = $.evalJSON(o);
        if (!o || !o.data || o.data.length < 1) {
            callback(o);
        }else{
            var d = o.data,k,gKey,inst,dt;
            for (var i = 0, l = d.length; i < l; i++) {
                inst=d[i]["inst"].split('.');
                gKey=inst[0]+":"+inst[2];
                if(!gData[gKey]){
                    gData[gKey]={};
                }
                dt=gData[gKey];
                for(var k in d[i]){
                    if($.inArray(k,xmlDataPoint)<0){
                        continue;
                    }
                    if (k == 'S1077') {//replace st198:P/E 
                        dt['st198'] = d[i][k];
                    }else if (k == 'S1086') {//replace pm032:Div Yield
                        dt['pm032'] = d[i][k];
                    }else if (k == 'S1087') {//replace sta65:Pro Yield
                        dt['sta65'] = d[i][k];
                    }else {
                        dt[k] = d[i][k];
                    }
                }
                dt['hasStaticDataFromXML']=true;
            }
            callback(o);
        }
    }); 
}

/* profile and management for workspace and desktop*/
var WorkspaceTabs = null;
var gWsList = {};
var wsWidgets = {};
var MstarData = {};
var lastModules = {};
var RtqDesktop;
var workspaceManager;
function getCurrModules() {
    if (WorkspaceTabs.currentTab && WorkspaceTabs.currentTab.modules)
        return WorkspaceTabs.currentTab.modules;
    return {};
}

/* la03z map for watchlist group by industry */
var LA03Z={
    "$VAL_UMKNOWN$":"Not Classified","101":"Basic Materials","308":"Communication Services","102":"Consumer Cyclical",
    "205":"Consumer Defensive","309":"Energy","103":"Financial Services","206":"Healthcare",
    "310":"Industrials","104":"Real Estate","311":"Technology","207":"Utilities" };


/*  Some functions provided to format the date or numbers*/
var d = new Date();
var startTick = new Date(d.getFullYear(), d.getMonth(), d.getDate()).getTime();
function FDate(value,islong) {
    var t = startTick + parseInt(value) * 1000;
    var dt = new Date(t);
    return (dt == null) ? "--" :(islong?DTFormat.ToLongTime(dt):DTFormat.ToShortTime(dt));
}

function formatDateString(str){// yyyymmdd to yyyy-mm-dd
    var t = [];
    var reg=/\d{4}-(0\d|1[0-2])-([0-2]\d|3[01])/;
    if(reg.exec(str)) return str;
    t.push(str.slice(0,4)),t.push(str.slice(4,6)),t.push(str.slice(6,8));
    return t.join("-");
}
function formatNameString(str){
    if(str==''||str==null){
        return str;
    }
    var t=str.split(" ");
    var t1=[];
    for(var i=0,l=t.length;i<l;i++){
        var firstChar=t[i].substring(0,1);
        var otherChars=t[i].substring(1);
        t1.push(firstChar.toUpperCase()+otherChars.toLowerCase());
    }
    return t1.join(" ");
}
function formatDoubledata(value,type,decimalpos,needformat,needunit,seperate,unmark,stayzs){
    var depos = "",returnvalue = "";
    if(String(value).trim().length==0) return returnvalue;
    if (typeof decimalpos=='undefined') {
        switch (type) {
            case "20"://forex  5
                depos = 5;
                break;
            case "1"://stock/fund
                depos = 2;
                break;
            case "10"://ETF
                depos = 2;
                break;
            default:
                depos = 2;
        }
    }
    else{
        depos = decimalpos;
    }
    if(needformat&&typeof QS_NumFmt!="undefined" && typeof QS_NumFmt.Fmt2 =='function'){
        if(unmark){
            returnvalue = QS_NumFmt.FmtUnMark(value,needunit||false,depos, needformat||false,stayzs||false);//n, isC, d,isFormat
        }else{
            returnvalue = QS_NumFmt.Fmt2(value,needunit||false,seperate||"",depos, needformat||false);//n, isC, sep, d,isFormat
        }
    }else{
        returnvalue = parseFloat(value).toFixed(depos);
    }
    return returnvalue;
}

/*generate unique id for components.*/
var idService = new function() {
    var prefix = 'opt_id_';
    var index = 0;
    var minusIndex = -2;

    this.newId = function() {
        index++;
        return prefix + index;
    };

    this.newMinusId = function() {
        return minusIndex--;
    };
};

/*override jQuery*/
jQuery.isArray = function(obj){
    return obj != null && typeof obj === "object" &&
    'splice' in obj &&
    'join' in obj;
};

/* override the methods of string*/
String.prototype.trim = function() {
    return this.replace(/^\s+|\s+$/g, "");
};

/* Default profile for each widgets*/
var widgetNames = {};
widgetNames[0] = "";
widgetNames[1] = "Chart:";
widgetNames[2] = "News:";
widgetNames[3] = "Quicktake:";
widgetNames[6] = "L2 MarketDepth:";

function getDefaultProfileByType(type) {
    var p = {};
    switch(parseInt(type,10))
    {
        case 0:{
            p = { name: "Watchlist", type: 0, widget: {}, x: 100, y: 100, w: 400, h: 300}}break;
        case 1:{
            p = { name: "Chart", type: 1, widget: {}, x: 100, y: 100, w: 760, h: 450 }}break;
        case 2:{
            p = { name: "News", type: 2, widget: { Ticker: "" }, x: 100, y: 100, w: 800, h: 320 }}break;
        case 3:{
            p = { name: "Quicktake", type: 3, widget: { Ticker: "" }, x: 100, y: 100, w: 1000, h: 600 }}break;
        case 6:{
            p = { name: "Market Depth", type: 6, widget: { Ticker: "" }, x: 100, y: 100, w: 442, h: 450 }}break;
        case 7:{
            p = { name: "Time & Sales", type: 7, widget: { Ticker: "" }, x: 100, y: 100, w: 405, h: 420 }}break;
        case 8:{
            p = { name: "Options", type: 8, widget: { Ticker: "" }, x: 100, y: 100, w: 925, h: 380, minWidth:800}}break;
        case 9:{
            p = { name: "Research", type: 9, widget: { Ticker: "IBM" }, x: 100, y: 100, w: 1000, h: 600 }}break;
        case 10:{
            p = { name: "Quote", type: 10, widget: { Ticker: "IBM" }, x: 100, y: 100, w: 365, h: 232 }}break;
        case 11:{
            p = { name: "Forex Dealing", type: 11, widget: { Ticker: "" }, x: 100, y: 100, w: 700, h: 470}}break;
        case 12:{
            p = {name: "Calendars",type: 12,widget: {Ticker: ""},x: 100,y: 100,w: 700,h: 470}}break;
        case 13:{
            p = {name: "Futures",type: 13,widget: {Ticker: ""},x: 100,y: 100,w: 850,h: 470}}break;
        case 14:{
            p = {name: "Market",type: 14,widget: {Ticker: ""},x: 100,y: 100,w: 200,h: 470}}break; 
        case 15:{
            p = {name: "Same Store Sales",type: 15,widget: {Ticker: ""},x: 100,y: 100,w: 470,h: 300}}break;
        case 16:{
            p = {name: "Cross Rates Table",type: 16,widget: {Ticker: ""},x: 100,y: 10,w: 800,h: 440}}break;
		case 18:{
	            p = {name: "Exchange Activity",type: 18, widget: {Ticker: ""},x: 100,y: 100,w: 900,h: 200,minWidth:600}}break;
		case 19:{
	            p = {name: "Gainers, Losers, Actives",type: 19, widget: {Ticker: ""},x: 100,y: 100,w: 650,h: 320}}break;
		case 27:{
	            p = {name: "Historical Price",type: 27, widget: {Ticker: ""},x: 100,y: 100,w: 650,h: 450, minWidth: 400}}break;
		case 21:{
	            p = {name: "Sector Screener",type: 21, widget: {Ticker: ""},x: 100,y: 100,w: 620,h: 500, minWidth: 600}}break;
		case 22:{
                p = {name: "News Overview",type: 22, widget: {showTitle:false},x: 100,y: 100,w: 460,h: 300}}break;
		case 23:{
				p = {name: "Calendars Overview",type: 23, widget: {Ticker:""},x: 100,y: 100,w: 250,h: 300,minWidth: 250}}break;
		case 26:{
			p = {name: "Advanced Search",type: 26, widget: {Ticker:""},x: 100,y: 100,w: 250,h: 300,minWidth: 400}}break;
		case 20:{
			p = {name: "Sharing",type: 27, widget: {Ticker:""},x: 100,y: 100,w: 250,h: 300,minWidth: 400}}break;
        case 30:{
            p = {name: "Fair Value",type: 30, widget: {},x: 100,y: 100,w: 600,h: 300,minWidth: 500}}break;			 
    }  
	 
    p.oldBox = {
        width: p.w,
        height: p.h,
        top: p.y,
        left: p.x
    };
    return p;
}



/*
 * New GOLBAL_DATA
 * David li 090907
 */
if (!GOLBAL_DATA) {
    var GOLBAL_DATA = {};
}
if(typeof GOLBAL_DATA.InstitutionSecuritityTypePermission=="undefined"){
     GOLBAL_DATA.InstitutionSecuritityTypePermission={
    "QUEST":{"ST":true,"FE":true,"XI":true}
}
}
if(typeof InstitutionId=="undefined"){
     InstitutionId = "QS";
}
//widget Template
GOLBAL_DATA.widgetTemplateList = {};
//[{title:'WatchlistA', id: 101},{title:'WatchlistB', id: 102},{title:'WatchlistC', id: 103}]; //Watchlist
GOLBAL_DATA.widgetTemplateList['0'] = []; 
GOLBAL_DATA.widgetTemplateList['01'] = []; //watchlis column view
GOLBAL_DATA.widgetTemplateList['1'] = []; //Charts
GOLBAL_DATA.widgetTemplateList['2'] = []; //News
GOLBAL_DATA.widgetTemplateList['21']=[];//News Custom view
GOLBAL_DATA.widgetTemplateList['51']=[];//saved search list
GOLBAL_DATA.widgetTemplateUpdateHistory = {};
GOLBAL_DATA.widgetTemplateUpdateHistory[0] = {};

GOLBAL_DATA.refreshTemplateListData = function(type,callback){
    DBHelper.getWidgetTemplateListByType(type, function(d){
        if(d == "")return;
        d = eval("("+d+")");
        GOLBAL_DATA.widgetTemplateList[type] = d.temp;
        if(callback){
            callback(GOLBAL_DATA.widgetTemplateList[type]);
        }
    });
};
GOLBAL_DATA.getTemplateListData = function(type, callback){
    if (GOLBAL_DATA.widgetTemplateList[type] && GOLBAL_DATA.widgetTemplateList[type].length > 0) {
        callback(GOLBAL_DATA.widgetTemplateList[type]);
    }
    else {
        GOLBAL_DATA.refreshTemplateListData(type, callback);
    }
};

/*
 * Terminal global profile
*/
/* interface for get and save profile of Terminal*/
if (!Terminal) {
    var Terminal = {};
}

Terminal.showLoading = function(){
    $("#terminal_loading").show();
};

Terminal.hideLoading = function(){
    $("#terminal_loading").hide();
};

Terminal.setConfig = function(config, callback){
    //Terminal.showLoading();
    for(var cf in config){
        GOLBAL_DATA.terminalGlobalProfile[cf] = config[cf];
    }
    callback = callback ||function(o){
            if ($.trim(o) == 'true') {
            }
            else {
            }
            //Terminal.hideLoading();
        };
    DBHelper.setGlobalProfile(GOLBAL_DATA.terminalGlobalProfile, callback);
};

Terminal.getConfig = function(name){
    return GOLBAL_DATA.terminalGlobalProfile[name];
};

Terminal.autoSave = function(fnSave){
    //var delay = 10000;
    var delay = 3000;
    var timer = -1;
    $(document).bind('mousemove', function(){
        if(timer){
            clearTimeout(timer);
            timer = -1;
        }
        timer = setTimeout(function(){
            fnSave();
        },delay);
    });
    //$(document).bind('mousemove', doSave);
};

/* ticker tape default setting*/
var tktp2dat = ["0P000001A2", "0P000000PA", "0P000002DO", "0P000005WD", "0P000000D5", "0P000003MH", "0P0000031C", "0P0000029A", 
                "0P000002X8", "0P0000019Y", "0P000004C0", "0P000004Z1", "0P000003PC", "0P0000023H", "0P0000043L"];
var tktp1dat = ["0P00002D7X", "0P00002DAS", "0P00002DCR", "0P00002DBM", "0P00002D8A", "0P00002D82", "0P00002DBQ", "0P00002DB8",
                 "0P00002DAJ", "0P00002DD5", "0P00002D92", "0P00002D97", "0P00002DBL", "0P00002DCP", "0P00002D9Z", "0P00002D98",
                 "0P00002D7Z", "0P00002D87", "0P00002DB4", "0P00002D80"];
var $tt1 = null; // ticker tape 1
var $tt2 = null; // ticker tape 2

/* Get size of screen */
var xDesktopW = $("body").width();
var xDesktopH = $("body").height()-((Terminal.getConfig('HideTickerTape') == false)?88:36) - ((Terminal.getConfig('HideToolbar') == true||typeof(QS_DetachWorkspaceID) != "undefined")?0:22);

/* For Watchlist Flash*/
var textKey = $.browser.msie?"innerText":"textContent"; 
function flashWithDirectional(el, v, c, isUp){ //v:current data, c:old data
    if(!v || !c){
        el.style.cssText = "background-color:" + QS_Style.normalFontBG + ";color:" + (isUp ? QS_Style.greenFlashFontColor : QS_Style.redFlashFontColor);
    }else{
        el.style.cssText = "background-color:" + ((v > c) ? QS_Style.greenFontBG : QS_Style.redFontBG)  + ";color:" + (isUp ? QS_Style.greenFlashFontColor : QS_Style.redFlashFontColor);
    }
    setTimeout(function(){
        el.style.cssText = "background-color:;color:" + (isUp ? QS_Style.greenFontColor : QS_Style.redFontColor);
    }, 300);
};
function flash(el, v, c){ //v:current data, c:old data
    if (!v || !c) {
        el.style.cssText = "background-color:" + QS_Style.normalFontBG + ";color:" + QS_Style.normalFlashFontColor;
    }
    else {
        el.style.cssText = "background-color:" + ((v > c) ? QS_Style.greenFontBG : QS_Style.redFontBG) + ";color:" + QS_Style.normalFlashFontColor;
    }
    setTimeout(function(){
        el.style.cssText = "background-color:;color:;";
    }, 300);
};

/* For detach widnows*/
var QS_DetachWindowResizable = false;
var _resizeTimeout = null;  // interval object fo detached Windows to resize.
var QS_DetachWindows={};
var QS_DefaultWsDetachWidgets = {};

 /* initalize a Calendar object in Terminal*/
if(typeof(Util.Calendar)!="undefined"){  
    QSCAL = new Util.Calendar($('body'),{},{});
}

/*some function to clean up the memory of widgets.*/
function clearWorkSpace(wsId){
    var tabItem = WorkspaceTabs.getTabById(wsId);
    if(tabItem){
        clearWigetsInTab(tabItem);
    }
}
function clearWigetsInTab(tab){
    if(tab&&tab.modules){
        for(var o in tab.modules){
            if(tab.modules[o].win){
                if(tab.modules[o].win.widget&&typeof(tab.modules[o].win.widget.clear)=="function"){
                    tab.modules[o].win.widget.clear();
                }
                if(typeof(tab.modules[o].win.clear)=="function"){
                    tab.modules[o].win.clear();
                }
            }
        }
    }
}
function clearAllWidgets(){
    if(WorkspaceTabs&&WorkspaceTabs.tabs&&WorkspaceTabs.tabs.length){
        for(var i=0;i<WorkspaceTabs.tabs.length;i++){
            clearWigetsInTab(WorkspaceTabs.tabs[i]);
        }
    }
}

/*For Workspace Navigation */
var navigateContainer = null, navigateIco = null,QS_Navigation;

/* previou load the image in IE to improve the performance*/
if(jQuery.browser.msie){
    var preLoadImage = new Image();// for toolbar bg
    preLoadImage.src = typeof(QS_Theme)!="undefined"&&QS_Theme.length? 'theme/' + QS_Theme + '/bg_toolbar.png' : 'IM/bg_toolbar.png';
}


/* colors setting for Theme*/
if (!QS_Style) {
    var QS_Style = {
        redFontColor: '#ff0000',
        redFontBG: '#FFC8C8',
        greenFontColor: '#008000',//
        greenFontBG: '#CDFFD7',
        normalFontBG:'#ccc',
        layouthelperBG:"#fff",
        redFlashFontColor:'#ff0000',
        greenFlashFontColor:'#008000',
        normalFlashFontColor:'#121212',
        chart:{
            tickerColors:["#728fb2", "#9b0033","#e96610","#f1ad02","#9faa00","#006065","#809aba","#e1b2c1",
                "#e2e5b2","#293f6f","#fbe6b3","#f2a370","#b2cfd0", "#bec5d4","#c5cc66","#f8d1b7","#c36685","#c9cbcb"],
            fillColors:{pChart:"#c9d2dd",vChart:"#2f4880",sChart:"#d9dfeb",minichartPchart:"#004DBC"}
        },
        flot:{grid:{color:"#545454",tickColor:"#dddddd"},alpha:0.7}
    };
}


var QS_heartBeat=function(url,timeout){
    var _time=timeout;
    var _id=null;
    var _url=url;
    return {
        startHeartBeat:function(){
              _id=setInterval(function(){
                 $.post(_url,{userID:QS_UserID});
              },_time);
        },
        stopHeartBeat:function(){
            clearInterval(_id);
        }
    }
}

/*Tell IE user to upgrade*/
if (jQuery.browser.msie && parseInt(jQuery.browser.version) < 8) {
    (function(){
        var IEVersion = jQuery.browser.version;
        var str = '<div class="please-upgrade" style="display:none;"><h2>Morningstar QuoteSpeed is best viewed in the following browsers.'+
                ' You\'ll still be able to launch QuoteSpeed in IE '+IEVersion+' but features may not work properly. <br/>'+
                '<br/>Please upgrade to any of the following browsers to continue:</h2><div class="browsers">'+
                '<a href="http://browserchoice.mozilla.com" class="ff">Firefox</a><a href="http://www.google.com/chrome" class="gc">'+
                'Google Chrome</a><a style="display:none;" href="http://www.apple.com/safari/" class="sf">Safari</a>'+
                '<a href="http://www.microsoft.com/windows/internet-explorer/choice/" class="ie">Internet Explorer 8</a>'+
                '</div><div class="action"><a href="#" class="continue">Continue using IE'+IEVersion+' anyway...</a></div></div>';
        var upgrade = $(str).appendTo(document.body);
        var mask = $('<div class="please-upgrade-mask" style="display:none;"></div>').appendTo(document.body);
        upgrade.find('.continue').click(function(e){
            upgrade.hide();
            mask.hide();
        });
        if (parseInt(jQuery.browser.version) < 7) {
            upgrade.show();
            mask.show();
        }
    }());
};


/* initalize terminal or global profile when document ready*/
$(document).ready(function() {
    //UserTrace
    //Qs_UserTrace.OperateComponent(Qs_UserTrace.Group.Basic, Qs_UserTrace.Source.Login, Qs_UserTrace.Oper.Open,null, null, new Date()-QS_Trace_startTime);
    
	if(typeof QS_LOADER=='undefined'){
		QS_LOADER = new QS.FileLoader({loadXMLConfig:{autoInit:true}});
	}
    $tt1 = $("#rtttickertape1");
    $tt2 = $("#rtttickertape2");
    
    var data;
    if(QS_DataType=='delay'||QS_DataType=='mix'){ // push mode
        data="streaming";
    }else{
        data=QS_DataType;
        GB_ChartDataManager.openDelayedPullData(); //pull mode and  open chart pull interface;
    }  
    QS.setDataMethod(data);
    
    // initalize the Rtqdesktop and workspaceManager Object.
    if(typeof(QSDesktopClass)!="undefined"){
        RtqDesktop = new QSDesktopClass();
    }
    if(typeof(workspaceManagerClass)!="undefined"){
        workspaceManager = new workspaceManagerClass();
        workspaceManager.init();
    } 
    //add navigation 
    
    /*navigateContainer = $('<div class="qs-navigation-container"></div>').appendTo(document.body).click(function(){
        navigateContainer.hide();
        navigateIco.show();
    }).css({width:(xDesktopW/6+5)+"px",height:(xDesktopH/6+5)+"px"});
    navigateIco = $('<div class="qs-navigation-ico"></div>').appendTo(document.body).click(function(){
        navigateContainer.show();
        var wsId = WorkspaceTabs.currentTab.id;
        QS_Navigation.draw(wsId);
        navigateIco.hide();
    });
    //QS_Navigation = new QS_NavigationChart(navigateContainer,{rate:{width:1/6,height:1/6}});
    navigateContainer.hide();
    */
   
    $(document).bind("keydown",function(e){
        if(e.keyCode==8&&e.target.nodeName.toUpperCase()!="INPUT"&&e.target.nodeName.toUpperCase()!="TEXTAREA"){
            return false; //Prevent user press the Backspace to go history
        }else if(e.keyCode==9){
            return false; //Prevent Tab key
        }
    });
    $(document).bind('contextmenu', function(){return false;}); // prevent the default context menu in browser.
    if(document.all){
        $("a[href='javascript:void(0)']").live("click",function (e){
            e.preventDefault();
        });
    }
	// update alert in watchlist
	if(QS_Alert_Data&&QS_Alert_Data.updateCheckAlertList){
		//QS_Alert_Data.updateCheckAlertList();
	}
    //hide loading icon
    $("#terminal_loading").hide();
    
    //var beforeunloadCount = 0;
    $.event.add(window, "beforeunload",function(){
        //beforeunloadCount ++;
        //if (beforeunloadCount == 1) {
            if (typeof(QS_DetachWorkspaceID) != "undefined" && typeof(QS_DetachType) != "undefined" && QS_DetachType == "zoomIn") { // zoomIn window.  save config and sync to the component.
                var widgetProfile, oProfile;
                var curTabItem = WorkspaceTabs.getTabById(QS_DetachWorkspaceID);
                if (curTabItem.modules[QS_DetachComponentID]) { // save the config of component in detach window.
                    var cWin = curTabItem.modules[QS_DetachComponentID].win;
                    if (cWin && cWin.widget && typeof(cWin.widget.saveConfig) == "function") {
                        widgetProfile = cWin.widget.saveConfig();
                    }
                }
                if (QS_DetachWorkspaceID < 0) { // default workspace.
                    oProfile = {};
                }else {
                    oProfile = window.wsWidgets[QS_DetachWorkspaceID][0].profile;
                }
                oProfile.widget = widgetProfile;
                var id = window.wsWidgets[QS_DetachWorkspaceID][0].id
                var parentWin = window.opener, config;
                for (var i = 0; i < parentWin.wsWidgets[QS_DetachWorkspaceID].length; i++) {
                    if (parentWin.wsWidgets[QS_DetachWorkspaceID][i]["id"] == id) {
                        delete oProfile.x, delete oProfile.y, delete oProfile.w, delete oProfile.h;
                        delete oProfile.state;
                        if (QS_DetachWorkspaceID < 0) { // default workspace.
                            config = $.extend(true, {
                                id: id,
                                profile: {}
                            }, {
                                profile: parentWin.wsWidgets[QS_DetachWorkspaceID][i].profile
                            }, {
                                profile: oProfile
                            });
                        }
                        else {
                            $.extend(true, parentWin.wsWidgets[QS_DetachWorkspaceID][i].profile, oProfile);
                            config = parentWin.wsWidgets[QS_DetachWorkspaceID][i];
                        }
                        break;
                    }
                }
                //workspaceManager.
                var tabItem = parentWin.WorkspaceTabs.getTabById(QS_DetachWorkspaceID);
                //parentWin.RtqDesktop.reBindMoudule(config,tabItem);
                Util.DelayRun('beforeunload_Detached', parentWin.RtqDesktop.reBindMoudule(config, tabItem), 10, window);
            //tabItem.modules=null;  // clear the all modules.
            //tabItem.loadModules();
            }else { // not deta
                for (var o in QS_DetachWindows) { // all the open windows.
                    if (QS_DetachWindows[o]) 
                        QS_DetachWindows[o].close();
                }
//              if (!workspaceManager.checkSaved() && typeof QS_DetachType == 'undefined') {//stop click <a>
//                  beforeunloadCount=0;
//                  return "Your changes are not saved.";
//              }
            }
//      }
    });
    $.event.add(window,"resize",function(){  // when detach window resize.
        if (typeof(QS_DetachWorkspaceID) != "undefined" && QS_DetachWindowResizable) { // detach window.
            clearInterval(_resizeTimeout);
            _resizeTimeout = setTimeout(function(){
                var tabItem = WorkspaceTabs.getTabById(QS_DetachWorkspaceID);
                var id = window.wsWidgets[QS_DetachWorkspaceID][0].id; // component ID.
                var win = tabItem.modules[id].win;
                win.setSize($(document.body).width(), $(document.body).height());
            }, 400);        
        }
    });
    // set a heart beat to web server to maintain the longe connection
    var heartBeat_terminal=new QS_heartBeat("heartbeat.jsp",1000*60*2);  
    heartBeat_terminal.startHeartBeat();
    // clear the memory of browse  when page unload.
    $.event.add(window, "unload",function(){
        clearAllWidgets();
        heartBeat_terminal.stopHeartBeat();
    });
});
